package net.lahuobao.finance.controller.accountsetting;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.hibernate.criterion.Property;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import org.jeecgframework.core.common.controller.BaseController;
import org.jeecgframework.core.common.hibernate.qbc.CriteriaQuery;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.common.model.json.DataGrid;
import org.jeecgframework.core.common.model.json.DataGridReturn;
import org.jeecgframework.core.constant.Globals;
import org.jeecgframework.core.util.StringUtil;
import org.jeecgframework.tag.core.easyui.TagUtil;
import org.jeecgframework.web.system.pojo.base.TSDepart;
import org.jeecgframework.web.system.pojo.base.TSUserOrg;
import org.jeecgframework.web.system.service.SystemService;
import org.jeecgframework.core.util.MyBeanUtils;

import net.lahuobao.finance.dao.CargoOwnerPayRatesMapper;
import net.lahuobao.finance.entity.accountsetting.AccountPaymentRatioSettingEntity;
import net.lahuobao.finance.service.accountsetting.AccountPaymentRatioSettingServiceI;

import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.jeecgframework.core.beanvalidator.BeanValidators;
import java.util.Set;
import javax.validation.ConstraintViolation;
import javax.validation.Validator;

import java.math.BigDecimal;
import java.net.URI;
import org.springframework.http.MediaType;
import org.springframework.web.util.UriComponentsBuilder;

/**   
 * @Title: Controller
 * @Description: 账户支付比例表
 * @author zhangdaihao
 * @date 2016-08-25 10:16:49
 * @version V1.0   
 *
 */
@Controller
@RequestMapping("/accountPaymentRatioSettingController")
public class AccountPaymentRatioSettingController extends BaseController {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(AccountPaymentRatioSettingController.class);

	@Autowired
	private AccountPaymentRatioSettingServiceI accountPaymentRatioSettingService;
	@Autowired
	private SystemService systemService;
	@Autowired
	private Validator validator;
	@Autowired
	private CargoOwnerPayRatesMapper cargoOwnerPayRatesDao;


	/**
	 * 账户支付比例表列表 页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "list")
	public ModelAndView list(HttpServletRequest request) {
		return new ModelAndView("net/lahuobao/finance/accountsetting/accountPaymentRatioSettingList");
	}

	/**
	 * easyui AJAX请求数据
	 * 
	 * @param request
	 * @param response
	 * @param dataGrid
	 * @param user
	 */

	@RequestMapping(params = "datagrid")
	public void datagrid(AccountPaymentRatioSettingEntity accountPaymentRatioSetting,HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
		
		CriteriaQuery cq = new CriteriaQuery(AccountPaymentRatioSettingEntity.class, dataGrid);
		
		//查询条件组装器
		org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, accountPaymentRatioSetting, request.getParameterMap());
		
		DataGridReturn dd = this.accountPaymentRatioSettingService.getDataGridReturn(cq, true);
			
		List<Map> list = new ArrayList<Map>();
		for(Object obj:dd.getRows()){
			AccountPaymentRatioSettingEntity ar = (AccountPaymentRatioSettingEntity)obj;
			Map map = new HashMap();
			if(null!=ar.getTSPDepart()){
				map.put("departname", ar.getTSPDepart().getDepartname());
			}
			map.put("id", ar.getId());
			map.put("aboutType", ar.getAboutType());
			map.put("oilAccountRatio", ar.getOilAccountRatio());
			map.put("etcAccountRatio", ar.getEtcAccountRatio());
			map.put("shopAccountRatio", ar.getShopAccountRatio());
			map.put("selfemployeeAccountRation", ar.getSelfemployeeAccountRation());
			list.add(map);
		}
		
		dataGrid.setResults(list);
		
		TagUtil.datagrid(response, dataGrid);
	}

	/**
	 * 删除账户支付比例表
	 * 
	 * @return
	 */
	@RequestMapping(params = "del")
	@ResponseBody
	public AjaxJson del(AccountPaymentRatioSettingEntity accountPaymentRatioSetting, HttpServletRequest request) {
		String message = null;
		AjaxJson j = new AjaxJson();
		accountPaymentRatioSetting = systemService.getEntity(AccountPaymentRatioSettingEntity.class, accountPaymentRatioSetting.getId());
		message = "账户支付比例表删除成功";
		accountPaymentRatioSettingService.delete(accountPaymentRatioSetting);
		systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
		
		j.setMsg(message);
		return j;
	}


	/**
	 * 添加账户支付比例表
	 * 
	 * @param ids
	 * @return
	 */
	@RequestMapping(params = "save")
	@ResponseBody
	public AjaxJson save(AccountPaymentRatioSettingEntity accountPaymentRatioSetting, HttpServletRequest request) {
		String message = null;
		AjaxJson j = new AjaxJson();
		String aboutId = request.getParameter("aboutId");
		TSDepart depart = systemService.getEntity(TSDepart.class, aboutId);
		systemService.getSession().evict(accountPaymentRatioSetting);
		accountPaymentRatioSetting.setTSPDepart(depart);
		if(null!=accountPaymentRatioSetting.getEtcAccountRatio()){
			accountPaymentRatioSetting.setEtcAccountRatio(accountPaymentRatioSetting.getEtcAccountRatio().divide(new BigDecimal("100")));
		}
		if(null!=accountPaymentRatioSetting.getOilAccountRatio()){
			accountPaymentRatioSetting.setOilAccountRatio(accountPaymentRatioSetting.getOilAccountRatio().divide(new BigDecimal("100")));
		}
		if(null!=accountPaymentRatioSetting.getSelfemployeeAccountRation()){
			accountPaymentRatioSetting.setSelfemployeeAccountRation(accountPaymentRatioSetting.getSelfemployeeAccountRation().divide(new BigDecimal("100")));
		}
		if(null!=accountPaymentRatioSetting.getShopAccountRatio()){
			accountPaymentRatioSetting.setShopAccountRatio(accountPaymentRatioSetting.getShopAccountRatio().divide(new BigDecimal("100")));
		}
		if (StringUtil.isNotEmpty(accountPaymentRatioSetting.getId())) {
			message = "账户支付比例表更新成功";
			AccountPaymentRatioSettingEntity t = accountPaymentRatioSettingService.get(AccountPaymentRatioSettingEntity.class, accountPaymentRatioSetting.getId());
			try {
				MyBeanUtils.copyBeanNotNull2Bean(accountPaymentRatioSetting, t);
				accountPaymentRatioSettingService.saveOrUpdate(t);
				systemService.addLog(message, Globals.Log_Type_UPDATE, Globals.Log_Leavel_INFO);
			} catch (Exception e) {
				e.printStackTrace();
				message = "账户支付比例表更新失败";
			}
		} else {
			message = "账户支付比例表添加成功";
			 
			accountPaymentRatioSettingService.save(accountPaymentRatioSetting);
			systemService.addLog(message, Globals.Log_Type_INSERT, Globals.Log_Leavel_INFO);
		}
		j.setMsg(message);
		return j;
	}

	@RequestMapping(params = "getDeparts")
	@ResponseBody
	public List<Map> getTsDepart( HttpServletRequest req){
		String aboutType = req.getParameter("aboutType");
		List<Map> list=null;

		if("1".equals(aboutType)){//承运商
			list=cargoOwnerPayRatesDao.getService();
		}
		if("2".equals(aboutType)){//服务商
			list=cargoOwnerPayRatesDao.getCarrier();
		}
		return list;
	}
	/**
	 * 账户支付比例表列表页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "addorupdate")
	public ModelAndView addorupdate(AccountPaymentRatioSettingEntity accountPaymentRatioSetting, HttpServletRequest req) {
		if (StringUtil.isNotEmpty(accountPaymentRatioSetting.getId())) {
			accountPaymentRatioSetting = accountPaymentRatioSettingService.getEntity(AccountPaymentRatioSettingEntity.class, accountPaymentRatioSetting.getId());
			systemService.getSession().evict(accountPaymentRatioSetting);
			TSDepart depart=accountPaymentRatioSetting.getTSPDepart();
		
			if(null!=accountPaymentRatioSetting.getEtcAccountRatio()){
				accountPaymentRatioSetting.setEtcAccountRatio(accountPaymentRatioSetting.getEtcAccountRatio().multiply(new BigDecimal("100")));
			}
			if(null!=accountPaymentRatioSetting.getOilAccountRatio()){
				accountPaymentRatioSetting.setOilAccountRatio(accountPaymentRatioSetting.getOilAccountRatio().multiply(new BigDecimal("100")));
			}
			if(null!=accountPaymentRatioSetting.getSelfemployeeAccountRation()){
				accountPaymentRatioSetting.setSelfemployeeAccountRation(accountPaymentRatioSetting.getSelfemployeeAccountRation().multiply(new BigDecimal("100")));
			}
			if(null!=accountPaymentRatioSetting.getShopAccountRatio()){
				accountPaymentRatioSetting.setShopAccountRatio(accountPaymentRatioSetting.getShopAccountRatio().multiply(new BigDecimal("100")));
			}
			List<Map> list=null;
			Integer aboutType = accountPaymentRatioSetting.getAboutType();
			if(aboutType.equals(1)){//承运商
				list=cargoOwnerPayRatesDao.getService();
			}
			if(aboutType.equals(2)){//服务商
				list=cargoOwnerPayRatesDao.getCarrier();
			}
			req.setAttribute("accountPaymentRatioSettingPage", accountPaymentRatioSetting);
			req.setAttribute("depart", depart);
			req.setAttribute("departs", list);
		}
		return new ModelAndView("net/lahuobao/finance/accountsetting/accountPaymentRatioSetting");
	}
	
	@RequestMapping(method = RequestMethod.GET)
	@ResponseBody
	public List<AccountPaymentRatioSettingEntity> list() {
		List<AccountPaymentRatioSettingEntity> listAccountPaymentRatioSettings=accountPaymentRatioSettingService.getList(AccountPaymentRatioSettingEntity.class);
		return listAccountPaymentRatioSettings;
	}
	
	@RequestMapping(value = "/{id}", method = RequestMethod.GET)
	@ResponseBody
	public ResponseEntity<?> get(@PathVariable("id") String id) {
		AccountPaymentRatioSettingEntity task = accountPaymentRatioSettingService.get(AccountPaymentRatioSettingEntity.class, id);
		if (task == null) {
			return new ResponseEntity(HttpStatus.NOT_FOUND);
		}
		return new ResponseEntity(task, HttpStatus.OK);
	}

	@RequestMapping(method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
	@ResponseBody
	public ResponseEntity<?> create(@RequestBody AccountPaymentRatioSettingEntity accountPaymentRatioSetting, UriComponentsBuilder uriBuilder) {
		//调用JSR303 Bean Validator进行校验，如果出错返回含400错误码及json格式的错误信息.
		Set<ConstraintViolation<AccountPaymentRatioSettingEntity>> failures = validator.validate(accountPaymentRatioSetting);
		if (!failures.isEmpty()) {
			return new ResponseEntity(BeanValidators.extractPropertyAndMessage(failures), HttpStatus.BAD_REQUEST);
		}

		//保存
		accountPaymentRatioSettingService.save(accountPaymentRatioSetting);

		//按照Restful风格约定，创建指向新任务的url, 也可以直接返回id或对象.
		Integer id = accountPaymentRatioSetting.getId();
		URI uri = uriBuilder.path("/rest/accountPaymentRatioSettingController/" + id).build().toUri();
		HttpHeaders headers = new HttpHeaders();
		headers.setLocation(uri);

		return new ResponseEntity(headers, HttpStatus.CREATED);
	}

	@RequestMapping(value = "/{id}", method = RequestMethod.PUT, consumes = MediaType.APPLICATION_JSON_VALUE)
	public ResponseEntity<?> update(@RequestBody AccountPaymentRatioSettingEntity accountPaymentRatioSetting) {
		//调用JSR303 Bean Validator进行校验，如果出错返回含400错误码及json格式的错误信息.
		Set<ConstraintViolation<AccountPaymentRatioSettingEntity>> failures = validator.validate(accountPaymentRatioSetting);
		if (!failures.isEmpty()) {
			return new ResponseEntity(BeanValidators.extractPropertyAndMessage(failures), HttpStatus.BAD_REQUEST);
		}

		//保存
		accountPaymentRatioSettingService.saveOrUpdate(accountPaymentRatioSetting);

		//按Restful约定，返回204状态码, 无内容. 也可以返回200状态码.
		return new ResponseEntity(HttpStatus.NO_CONTENT);
	}

	@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
	@ResponseStatus(HttpStatus.NO_CONTENT)
	public void delete(@PathVariable("id") String id) {
		accountPaymentRatioSettingService.deleteEntityById(AccountPaymentRatioSettingEntity.class, id);
	}
}
